package com.xl.sqlSession;

import com.xl.config.BoundSql;
import com.xl.pojo.Configuration;
import com.xl.pojo.MappedStatement;
import com.xl.utils.GenericTokenParser;
import com.xl.utils.ParameterMapping;
import com.xl.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws Exception {
        //注册驱动，获取连接
        Connection connection = configuration.getDataSource().getConnection();
        //获取sql select * from user where id = #{id} and name = #{name}
        String sql = mappedStatement.getSql();
        //转换sql select * from user where id = ? and name = ? 因为jdbc 只识别？占位符，转换的过程中，还需要对#{}
        //里面的值进行解析存储
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象PreparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getParseSql());

        //设置参数
        //获取入参类型 com.xl.jdbc.pojo.User
        String paramterType = mappedStatement.getParamterType();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        for (int i = 0; i < parameterMappings.size(); i++) {
            Class<?> paramterTypeClass = Class.forName(paramterType);
            ParameterMapping parameterMapping = parameterMappings.get(i);
            //获取参数名称 比如id name
            String filed = parameterMapping.getContent();
            //利用反射获取参数值
            Field declaredField = paramterTypeClass.getDeclaredField(filed);
            declaredField.setAccessible(true);
            Object value = declaredField.get(params[0]);
            preparedStatement.setObject(i+1,value);
        }

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        //获取输出参数类型 com.xl.jdbc.pojo.User
        String resultTypeStr = mappedStatement.getResultType();
        Class<?> resultTypeClass = Class.forName(resultTypeStr);
        List<Object> relsutList = new ArrayList<>();
        //封装返回结果集
        while (resultSet.next()){
            //返回实体
            Object obj = resultTypeClass.newInstance();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            //列数
            int columnCount = metaData.getColumnCount();
            for (int i = 1; i <= columnCount; i++) {
                //字段名
                String columnName = metaData.getColumnName(i);
                //字段值
                Object value = resultSet.getObject(columnName);
                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(obj,value);
            }
            relsutList.add(obj);
        }

        return (List<E>) relsutList;
    }

    /**
     * 完成对#{}的解析工作：1.将#{}使用？代替  2.解析出#{}里面的值进行存储 如id name
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        //使用mybatis工具类
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{","}",parameterMappingTokenHandler);
        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parseSql,parameterMappings);
    }
}
